package com.ansion.baseui.base.click;

import android.os.SystemClock;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * created by zhaoyuntao
 * on 2020/6/12
 * description:Avoid clicking twice in one press.
 */
public class AvoidDoubleClickListener implements View.OnClickListener {

    private long duration = 300;
    private long timeOfClick;
    @Nullable
    private View.OnClickListener listener;

    public AvoidDoubleClickListener() {
    }

    public AvoidDoubleClickListener(@Nullable View.OnClickListener listener) {
        this.listener = listener;
    }

    public AvoidDoubleClickListener(long duration) {
        this.duration = duration;
    }

    @Override
    final public void onClick(View view) {
        long timeNow = SystemClock.elapsedRealtime();
        long timePassed = timeNow - timeOfClick;
        boolean tooFrequently = timePassed < duration;
        onClickView(view, tooFrequently);
        if (!tooFrequently) {
            timeOfClick = timeNow;
            if (listener != null) {
                listener.onClick(view);
            }
            onClickView(view);
        }
    }

    public void onClickView(View view) {

    }

    public void onClickView(View view, boolean tooFrequently) {
    }
}
